package com.boilerCloud.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;




public class FileUtil {
	public static final Logger logger = Logger.getLogger(FileUtil.class);
	private static String FILESERVER = Configuration.readConfigString("fileserver");
	private static String FILESERVER_VIDEO = Configuration.readConfigString("fileserver_video");
	public static String FILEUPLOADROOT = Configuration.readConfigString("FILE_UPLOAD_ROOT");
	
	
	/*public  static String  upload(File file) throws IOException{
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = UUID.randomUUID().toString().replace("-", "").trim();
		
			InputStream inputStream = new FileInputStream(file);
			String result = "";
			URL url = new URL(FILESERVER);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			httpURLConnection.setRequestProperty("Session-Param", "0|" + file.length());
			// Convert-ID
			//0或者注释后不进行转换
			//2无错误日志，100DPI，G3
			//3输出调用gm错误日志，100DPI，G3
			//4无错误日志，200DPI，G3
			//5输出调用gm错误日志，200DPI，G3
			//6不转换且输出图片页数
			//7无错误日志，100DPI，LZW
			//8输出调用gm错误日志，100DPI，LZW
			//9无错误日志，200DPI，LZW
			//10输出调用gm错误日志，200DPI，LZW
			httpURLConnection.setRequestProperty("Convert-ID", 0+"");
			httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + end);
			String name = new String(Base64.encodeBase64(file.getName().getBytes()), "UTF-8"); 
			String str = new String(file.getName().getBytes(),"UTF-8"); 
			String strs = file.getName().substring(file.getName().lastIndexOf("."));
			dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + System.currentTimeMillis()+ strs+ "\"" + end);
			dos.writeBytes(end);
			byte[] buffer = new byte[16384]; // 16k
			int count = 0;
			while ((count = inputStream.read(buffer)) != -1) {
				dos.write(buffer, 0, count);
			}
			inputStream.close();
			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();
			if (httpURLConnection.getResponseCode() == 200) {
				InputStream is = httpURLConnection.getInputStream();
				InputStreamReader isr = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				result = br.readLine();
				//注意：再调用一次br.readLine()获取页数，如果转换失败页数返回0
				is.close();
			} else {
				logger.error("文件上传到文件服务器返回错误http码:{}",new Exception(""+httpURLConnection.getResponseCode()));
			}
			dos.close();
			return result;
	}*/
	
	public static byte[] downloadFileByUrl(String path)throws Exception{
        URL url = new URL(path);
        URLConnection conn =null;
        try {
            conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); 
            byte[] b = new byte[1000];
            int size = 0;
            while((size = inStream.read(b))!=-1){
            	bos.write(b,0,size);
            }
            bos.close();
            inStream.close();
            return bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally{
        	if(conn!=null){
        		conn=null;
        	}
        }
	}

	public static String getFileType(String suffix){
		String type = "5";
		if(suffix.toLowerCase().equals(".jpg")||suffix.toLowerCase().equals(".png")||suffix.toLowerCase().equals(".gif")||suffix.toLowerCase().equals(".bmp")||suffix.toLowerCase().equals(".tif")||suffix.toLowerCase().equals(".ico")){
			type="0";
		}
		else if(suffix.toLowerCase().equals(".doc")||suffix.toLowerCase().equals(".docx")||suffix.toLowerCase().equals(".xls")||suffix.toLowerCase().equals(".xlsx")||suffix.toLowerCase().equals(".ppt")){
			type="1";
		}
		else if(suffix.toLowerCase().equals(".mp3")||suffix.toLowerCase().equals(".wav")||suffix.toLowerCase().equals(".cda")||suffix.toLowerCase().equals(".mid")){
			type="2";
		}
		else if(suffix.toLowerCase().equals(".avi")||suffix.toLowerCase().equals(".rm")||suffix.toLowerCase().equals(".rmvb")||suffix.toLowerCase().equals(".mpg")||suffix.toLowerCase().equals(".mpeg")||suffix.toLowerCase().equals(".3gp")||suffix.toLowerCase().equals(".flv")||suffix.toLowerCase().equals(".mp4")||suffix.toLowerCase().equals(".dat")||suffix.toLowerCase().equals(".m4v")||suffix.toLowerCase().equals(".mov")){
			type="3";
		}else{
			type="5";
		}
		return type;
	}
	/* public static String getFileUrl(byte[] bfile, String fileName) throws IOException {  
	        BufferedOutputStream bos = null;  
	        FileOutputStream fos = null;  
	        File file = null;
	            File dir = new File(FILEUPLOADROOT);  
	            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在  
	                dir.mkdirs();  
	            }  
	            file = new File(FILEUPLOADROOT+"\\"+fileName);  
	            fos = new FileOutputStream(file);  
	            bos = new BufferedOutputStream(fos);  
	            bos.write(bfile);
	            bos.flush();
	            fos.flush();
	            bos.close();
	            fos.close();
	            String url = upload(file);
	            file.deleteOnExit();
	            return url;
	 }*/
	 
	/* *//**
	  * 文件服务器上传
	  * @param filePath
	  * @param fileName
	  * @return
	  * @throws IOException
	  *//*
	 public static String getFileUrl(String filePath, String fileName) throws IOException {  
	        File file = new File(filePath+File.separator+fileName);
	        String url="";
	        if(file.exists()){
	        	url = upload(file);
	        	return url;
	        }
            return "";
	 }*/
	 
	 /**
	  * 删除目录及以下所有文件
	  * @param f
	  * @return
	  * @throws IOException
	  */
	 public static boolean del(File f) throws IOException {
		 boolean r=false;  
	        if (f.exists() ) {// 判断是文件还是目录  
	            r=f.delete();  
	        }else if(f.isDirectory()){  
	            if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除  
	                r=f.delete();  
	            } else {// 若有则把文件放进数组，并判断是否有下级目录  
	                File delFile[] = f.listFiles();  
	                int i = f.listFiles().length;  
	                  
	                for (int j = 0; j < i; j++) {  
	                    if (delFile[j].isDirectory()) {  
	                        del(delFile[j]);// 递归调用del方法并取得子目录路径  
	                    }  
	                    r=delFile[j].delete();// 删除文件  
	                }  
	                  
	            }  
	        }  
	        return r; 
	 }
	 
	 public static boolean del(String filepath) throws IOException {  
	       File f = new File(filepath);// 定义文件路径  
	       return del(f);
	 }  
	 
	 /**
	  * 上传视频并转换为MP4格式
	  * @param httpUrl
	  * @param parameters 
	  * @param inputStream 文件数据  
	  * @param filename  上传的文件名称，1.doc
	  * @param filesize 文件大小
	  * @return
	  */
	public static String uploadFile(Map<String, Object> parameters, InputStream inputStream, String filename,long filesize)
	{
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = UUID.randomUUID().toString().replace("-", "").trim();

		try {
			System.out.println("==========enter===========");
			long start=System.currentTimeMillis();
			String result = "";
			URL url = new URL(FILESERVER_VIDEO);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			long end1=System.currentTimeMillis();
			System.out.println("连接耗时"+(end1-start));
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + end);
			dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"" + end);
			dos.writeBytes(end);
			byte[] buffer = new byte[163840]; // 16k
			int count = 0;
			while ((count = inputStream.read(buffer)) != -1) {
				dos.write(buffer, 0, count);
			}
			inputStream.close();
			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();
			long end2=System.currentTimeMillis();
			System.out.println("上传耗时"+(end2-end1));
			if (httpURLConnection.getResponseCode() == 200) {
				InputStream is = httpURLConnection.getInputStream();
				InputStreamReader isr = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				result = br.readLine();
				//注意：再调用br.readLine()获取文档页数或文件字节数
				is.close();
			} else {
				result = String.valueOf(httpURLConnection.getResponseCode());
			}
			dos.close();
			long end3=System.currentTimeMillis();
			System.out.println("返回耗时 "+(end3-end2));
			System.out.println("总耗时 "+(end3-start));
			System.out.println("==============get back=============");
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return "101";
		}
	}

	
	public static String getFileUrl(String filePath, String fileName) { 

         return QNFileUpload.upload(filePath+File.separator+fileName,fileName);
	}
	
	public static String upload(String root,String tempPath)throws Exception{
		if (tempPath.indexOf("../temp") > -1) {
			// 封面转存到文件服务器
			tempPath = tempPath.substring(tempPath.indexOf("/"));	
			String str = FileUtil.getFileUrl(root, tempPath);
			FileUtil.del(root + tempPath);
			
			return str;
		}
		return tempPath;
	}
	
	
	public  static String  upload(String path){
		return QNFileUpload.upload(path, path.substring(path.lastIndexOf(File.separator)+1, path.length()));
	}
}


